package com.xuecheng.manage_cms.service.impl;

import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.request.QueryPageRequest;
import com.xuecheng.framework.domain.cms.response.CmsCode;
import com.xuecheng.framework.domain.cms.response.CmsPageResult;
import com.xuecheng.framework.domain.course.response.CourseCode;
import com.xuecheng.framework.domain.course.response.PreviewResult;
import com.xuecheng.framework.domain.course.response.PublishResult;
import com.xuecheng.framework.exception.CustomException;
import com.xuecheng.framework.exception.CustomExcetionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.framework.model.response.ResultCode;
import com.xuecheng.manage_cms.dao.CmsPageRepository;
import com.xuecheng.manage_cms.service.CmsConfigService;
import com.xuecheng.manage_cms.service.CmsPageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.net.ConnectException;
import java.util.List;
import java.util.Optional;

/**
 * @Description:
 * @Param:
 * @return:
 * @Author: Mr.Yuan
 * @Date:
 */
@Service
public class CmsPageServiceImpl implements CmsPageService {
    @Autowired
    private CmsPageRepository cmsPageRepository;
    @Autowired
    private CmsConfigServiceImpl cmsConfigService;

    @Override
    public QueryResponseResult findList(int page, int size, QueryPageRequest queryPageRequest) {
        if (queryPageRequest == null) {
            QueryPageRequest queryPageRequest1 = new QueryPageRequest();
        }
        CmsPage cmsPage = new CmsPage();
        String pageAliase = queryPageRequest.getPageAliase();
        String siteId = queryPageRequest.getSiteId();
        String templateId = queryPageRequest.getTemplateId();
        String pageName = queryPageRequest.getPageName();
        String pageType = queryPageRequest.getPageType();

        if (!StringUtils.isEmpty(pageAliase)) {
            cmsPage.setPageAliase(pageAliase);
        }
        if (!StringUtils.isEmpty(siteId)) {
            cmsPage.setSiteId(siteId);
        }
        if (!StringUtils.isEmpty(templateId)) {
            cmsPage.setTemplateId(templateId);
        }
        if (!StringUtils.isEmpty(pageName)) {
            cmsPage.setPageName(pageName);
        }
        if (!StringUtils.isEmpty(pageType)) {
            cmsPage.setPageType(pageType);
        }

        ExampleMatcher matcher = ExampleMatcher.matching();
        matcher = matcher.withMatcher(
                "pageAliase", ExampleMatcher.GenericPropertyMatchers.contains()).
                withMatcher(
                        "pageName", ExampleMatcher.GenericPropertyMatchers.contains()
                ).withMatcher(
                "pageType", ExampleMatcher.GenericPropertyMatchers.exact()
        );
        Example<CmsPage> example = Example.of(cmsPage, matcher);

        if (page <= 0) {
            page = 1;
        }
        page = page - 1;
        if (size <= 0) {
            size = 10;
        }
        Pageable pageable = PageRequest.of(page, size);
        Page<CmsPage> cmsPages = cmsPageRepository.findAll(example, pageable);

        ResultCode resultCode = CommonCode.SUCCESS;
        QueryResult queryResult = new QueryResult();

        queryResult.setList(cmsPages.getContent());
        queryResult.setTotal(cmsPages.getTotalElements());
        QueryResponseResult queryResponseResult = new QueryResponseResult(resultCode, queryResult);

        return queryResponseResult;

    }

    @Override
    public CmsPageResult add(CmsPage cmsPage) {
//        根据索引，先判断数据是否重复
        CmsPage findcmsPage = cmsPageRepository.findByPageNameAndAndPageWebPathAndSiteId
                (cmsPage.getPageName(), cmsPage.getPageWebPath(), cmsPage.getSiteId());
        if (findcmsPage != null) {
//            异常

            throw CustomExcetionCast.getCusException(CmsCode.CMS_ADDPAGE_EXISTSNAME);
        }

//            进行存储
        CmsPage save = cmsPageRepository.save(cmsPage);
        return new CmsPageResult(CommonCode.SUCCESS, save);


    }

    //根据页面id查询数据库
    @Override
    public CmsPageResult findById(String id) {
        if (id == null) {
            throw CustomExcetionCast.getCusException(CmsCode.CMS_GENERATEHTML_DATAISNULL);
        }
//            查询数据库
        Optional<CmsPage> pageOptional = cmsPageRepository.findById(id);

        if (pageOptional.isPresent()) {
            CmsPage cmsPage = pageOptional.get();
            return new CmsPageResult(CommonCode.SUCCESS, cmsPage);
        } else {
            throw CustomExcetionCast.getCusException(CmsCode.CMS_GENERATEHTML_DATAISNULL);
        }
    }


    @Override
    public CmsPageResult update(String id, CmsPage cmsPage) {
        if (cmsPage == null) {
            throw CustomExcetionCast.getCusException(CmsCode.CMS_GENERATEHTML_DATAURLISNULL);
        }
        CmsPageResult findPage = this.findById(id);
        CmsPage page = findPage.getCmsPage();
        if (page == null) {
            throw CustomExcetionCast.getCusException(CmsCode.CMS_GENERATEHTML_DATAURLISNULL);
        }

        page.setTemplateId(cmsPage.getTemplateId());
        //更新所属站点
        page.setSiteId(cmsPage.getSiteId());
        //更新页面别名
        page.setPageAliase(cmsPage.getPageAliase());
        //更新页面名称
        page.setPageName(cmsPage.getPageName());
        //更新访问路径
        page.setPageWebPath(cmsPage.getPageWebPath());
        //更新物理路径
        page.setPagePhysicalPath(cmsPage.getPagePhysicalPath());
//        更新数据url
        page.setDataUrl(cmsPage.getDataUrl());
        //执行更新
        cmsPageRepository.save(page);
        return new CmsPageResult(CommonCode.SUCCESS, page);


    }

    @Override
    public CmsPageResult delete(String id) {
        if (!StringUtils.isEmpty(id)) {
            CmsPageResult result = this.findById(id);
            CmsPage cmsPage = result.getCmsPage();
            if (cmsPage != null) {
                cmsPageRepository.deleteById(id);
                return new CmsPageResult(CommonCode.SUCCESS, null);
            }
        }
        return new CmsPageResult(CommonCode.FAIL, null);
    }

    /**
     * @Description: 保存页面信息
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    @Override
    public CmsPageResult savePageByCourse(CmsPage cmsPage) {
        if (cmsPage == null) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        String pageName = cmsPage.getPageName();
        String pageWebPath = cmsPage.getPageWebPath();
        String siteId = cmsPage.getSiteId();
        if (StringUtils.isEmpty(pageName) || StringUtils.isEmpty(pageWebPath) || StringUtils.isEmpty(siteId)) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        CmsPage cmsPage1 = cmsPageRepository.findByPageNameAndAndPageWebPathAndSiteId(pageName, pageWebPath, siteId);
        if (cmsPage1 == null) {
            CmsPage page = cmsPageRepository.save(cmsPage);
            return new CmsPageResult(CommonCode.SUCCESS, cmsPage);
        } else {

            CmsPageResult update = this.update(cmsPage1.getPageId(), cmsPage);
            return update;
        }
    }

    /**
     * @Description: 一键发布
     * @Param:  cmpspage
     * @return: 发布结果
     * @Author: Mr.Yuan
     * @Date:
     */
    @Override
    public PublishResult oneKeyPublish(CmsPage cmsPage) {
//        将页面信息保存到数据库中
        CmsPageResult cmsPageResult = savePageByCourse(cmsPage);
        if(cmsPageResult.getCmsPage()==null||StringUtils.isEmpty(cmsPageResult.getCmsPage().getPageId())){
            throw  CustomExcetionCast.getCusException(CommonCode.SERVER_ERROR);
        }
        String pageId = cmsPageResult.getCmsPage().getPageId();
//        调用静态化方法，进行页面静态化
        String html = cmsConfigService.getHtml(pageId);
        cmsConfigService.storeHtml(pageId,html);
//        将静态化的信息通过RabbitMQ通知消费端接口，修改页面
        cmsConfigService.producer(pageId);
        return new PublishResult(CommonCode.SUCCESS) ;
    }
}
